<?php
/**
 * 21天减重测评算法
 * Created by PhpStorm.
 * User: liao
 * Date: 2016/12/12
 * Time: 16:41
 */

namespace App\Services\Result;

use App\Interf\Resultable;
use Monolog\Logger;
use TestingConfig;
use App\Services\OpensslEncryptHelper;
use App\Models\LogHelper;
use WechatUserService;
class MetaWeightResult extends BaseResult implements Resultable
{
    private $uid;
    private $tid;
    private $answers;
    private $freeOrderId;
    /**肥胖指数*/
    private $fatFactorAttrObj;
    /**身体概述*/
    //private $bodySummaryAttrObj;
    /**健康指数*/
    //private $healthFactorAttrObj;
    /**减重阻力*/
    //private $dwResistAttrObj;

    public function __construct($answersStr = null, $freeOrderId,$uid,$tid)
    {
        $this->uid=$uid;
        $this->tid=$tid;
        $this->freeOrderId = $freeOrderId;
        $this->answers = $this->convertAnswer($answersStr);
        $this->fatFactorAttrObj = $this->configAttrObj(1, '轻体营');
        //$this->bodySummaryAttrObj = $this->configAttrObj(2,'身材概述');
        //$this->healthFactorAttrObj = $this->configAttrObj(3,'健康指数');
        //$this->dwResistAttrObj = $this->configAttrObj(4,'减重阻力');
    }

    public function result()
    {
//        $attrs = [];
//        $index = 27;
//        $answerWeight = 5;
//        $result = $this->getItemResult($index,$answerWeight);
//        return $result;
        $attrs = [];
        /*减肥指数*/
        array_push($attrs, $this->getFatAttr());
        /*身材概述*/
        //array_push($attrs,$this->getBodySummaryAttr());
        /**健康指数*/
        //array_push($attrs,$this->getHealthAttr());
        /**减重阻力*/
        //array_push($attrs,$this->getDecreaseResistanceAttr());
        $data['attrs'] = $attrs;
        //$data['chatparam'] = $this->getChatparam();
        $data['chatparam'] = "";
        //图类型常规图
        $data['chatType'] = $this->getChatType();
        return $data;
    }


    /**
     * 肥胖指数
     */
    protected function getFatAttr()
    {
        $note = '';
        //第一部分的结论
        // $note .= $this->getFatResultFirstNote();
        //第24道题
        //$this->getNoteByIndex($note,22);
        //腰围结论部分标题
        /* $answer28 = $this->getDefaultAnswerObjByIndex(28);
         if($answer28['weight']>0){
             $fatWaistTitle = ParamConfig::getValue('Elboo.fat.waist.title');
             $note .= $fatWaistTitle;
         }
         //获取腰围的计算结果
         $note .= $this->getFatWaistResult();*/
        $list = $this->getParam();
        //获取额外部分
        $extra = null;
        $this->getNutriContact($note);
        $obj = $this->fatFactorAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'], $obj['title'], $note, $extra);
        $obj['list'] = $list;
        return $obj;
    }

    /**
     * @return array
     */
    protected function getParam(){
        $data = [];
        $orderInfo = $this->getOrderInfoFromJz();
        $data = array_merge($data,$orderInfo);
        $userInfo = $this->getUserInfoByUid($this->uid);
        $data = array_merge($data,$userInfo);
        $reasonable = $this->getReasonableWeight();
        $data = array_merge($data,$reasonable);
        return $data;
    }

    /**获取订单内部编号
     * @return mixed|string
     */
    protected function getOrderInfoFromJz()
    {
        $inner_no = "";
        if ($this->freeOrderId) {
            $baseUrl = TestingConfig::getValue('jz.admin.base.url');
            //$baseUrl = 'http://localhost/lose_fat/public/index.php';
            $path = TestingConfig::getValue('jz.free_order.result.path');
            $url = $baseUrl.$path;
            $data['id'] = $this->freeOrderId;
            $str = json_encode($data);
            $encode = OpensslEncryptHelper::encryptWithOpenssl($str);
            $url = sprintf($url,$encode);
            $data = curlRequest($url, [], 'get');
            $data = json_decode($data,true);
            if($data['errcode'] == 200){
                $inner_no = $data['data']['inner_no'];
            }
        }
        $datas['inner_no'] = $inner_no;
        return $datas;
    }

    /**获取用户信息
     * @param $uid
     * @return mixed
     */
    protected function getUserInfoByUid($uid){
        $user = WechatUserService::getByUid($uid);
        $nick_name = "";
        $head = "";
        if($user){
            $nick_name = $user['nick_name'];
            $head = $user['headimgurl'] ? str_replace('min','max',WechatUserService::buildUserAvatarUrl($user['headimgurl'])) : "";
        }
        $data['nick_name'] = $nick_name;
        $data['head'] = $head;
        return $data;
    }


    /**获取合理的减重
     * @return mixed
     */
    protected function getReasonableWeight(){
        $goalWeight = $this->getDefaultAnswerObjByIndex(9);
        $weight = $this->getDefaultAnswerObjByIndex(8);
        $height = $this->getDefaultAnswerObjByIndex(7);
        $optimum = round((min($weight['answer']*0.05,($weight['answer']-$height['answer']*$height['answer']*18.5/10000)))*2);
        $data['goal'] = (int)$goalWeight['answer'];
        $data['optimum'] = $optimum;
        $data['reasonable'] = $goalWeight['answer'] > $optimum ? false : true;
        return $data;
    }











    /**
     * 获取肥胖指数第一个结论部分
     */
    protected function getFatResultFirstNote()
    {
        $result = ParamConfig::getValue('qiezi.currency.fat.result.first.note');
        $answer19 = $this->getDefaultAnswerObjByIndex(19);
        $answer29 = $this->getDefaultAnswerObjByIndex(29);
        $result = str_replace('$19', $answer19['answer'], $result);
        $result = str_replace('@29', round($answer29['weight'], 2) . '%', $result);
        return $result;
    }

    protected function getNutriContact(&$note)
    {
        //$itemNinteenObjTitle = TestingConfig::getValue('DW.resist.item.14.result');
        $note .= "";
    }


    protected function getDefaultAnswerObjByIndex($index)
    {
        $obj = [];
        foreach ($this->answers as $answer) {
            if ($index == $answer['index']) {
                $obj = $answer;
                break;
            }
        }
        return $obj;
    }

    protected function getNoteByIndex(&$note, $index)
    {
        $obj = $this->getDefaultAnswerObjByIndex($index);
        $note .= $this->getItemResult($obj['index'], $obj['weight']);
    }

    /**
     * 获取单个问题通过条件判断后最终的结果
     */
    protected function getItemResult($index, $answerWeight)
    {
        $result = '';
        $values = $this->getSingleItemConfig($index);
        if (count($values) > 0) {
            foreach ($values as $val) {
                $expression = $val['key'];
                if ($data = $this->getQuestionItemCondResult($expression, $answerWeight)) {
                    $result = $val['value'];
                    break;
                }
            }
        }
        return $result;
    }

    /**
     * 获取减重测评单个题目对应的配置信息
     */
    protected function getSingleItemConfig($index)
    {
        $values = ParamConfig::getDWTestingValuesByTag($index);
        return $values;
    }


    /**
     * 获取单个题目对应的条件判断值
     */
    protected function getQuestionItemCondResult($expression, $originVal)
    {
        $expression = $expression . '?1:0;';
        $result = $this->compactExpress($expression, $originVal);
        return $result;
    }

    /**
     * 组装表达式,这里充分的利用eval函数可以计算的功能
     * @param string $expression 原始表达式
     * @param string $orgVal 原始值
     * @return string
     */
    protected function compactExpress($expression, $orgVal)
    {
        $val = '$val=$orgVal;$val=' . $expression;
        eval($val);
        return $val;
    }


    /**将answer转换为数组
     * @param $answerStr
     * @return array
     */
    protected function convertAnswer($answerStr)
    {
        $answers = [];
        $answerArr = explode('##', $answerStr);
        if (count($answerArr) > 0) {
            foreach ($answerArr as $answer) {
                $singleArr = explode(':', $answer);
                if (count($singleArr) > 0) {
                    $obj['index'] = $singleArr[0];
                    $obj['weight'] = $singleArr[1];
                    $obj['answer'] = $singleArr[2];
                    array_push($answers, $obj);
                }
            }
        }
        return $answers;
    }

    protected function compactAttrObj($id, $title, $note, $extra = '')
    {
        return [
            'attr_id' => $id,
            'title' => $title,
            'note' => $note,
            'extra' => $extra,
        ];
    }



    /**
     * 身材概述
     */
    /*protected function getBodySummaryAttr(){
        $note = '';
        //第五道题
        $this->getNoteByIndex($note,5);
        //获取第六道题
        $itemSixObj = $this->getDefaultAnswerObjByIndex(6);
        $itemSixObjTitle = ParamConfig::getValue('FW.resist.item.6.start');
        //替换数据口中的@6，显示血型
        $itemSixObjTitle = str_replace('@6',$itemSixObj['answer'],$itemSixObjTitle);
        //拼接第六道题的描述
        $note .= $itemSixObjTitle.'<br/>';
        //第6道
        $this->getNoteByIndex($note,6);
        $this->getNutriContact($note);
        $obj = $this->bodySummaryAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note);
        return $obj;
    }*/


    /**
     * 健康指数
     */
    /*protected function getHealthAttr(){
        $note = '';
        //第25道题
        $this->getNoteByIndex($note,26);
        //第26道题
        $this->getNoteByIndex($note,27);
        $answer17 = $this->getDefaultAnswerObjByIndex(17);
        if($answer17['weight']>0){
            //额外的健康因素
            $itemExtraTitleObj = ParamConfig::getValue('FW.health.life.extra.title');
            $note .= $itemExtraTitleObj;
            //第17道题
            $this->getNoteByIndex($note,17);
        }
        $this->getNutriContact($note);
        $obj = $this->healthFactorAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note);
        return $obj;
    }*/


    /**
     * 减重阻力
     */
    /*protected function getDecreaseResistanceAttr(){
        $note = '';
        //第27道题
        $this->getNoteByIndex($note,28);
        //获取第18道题
        $itemNineteenObj = $this->getDefaultAnswerObjByIndex(18);
        if(intval($itemNineteenObj['weight'])>0){
            $itemNinteenObjTitleObj = ParamConfig::getValue('FW.resist.item.18');
            $note .= $itemNinteenObjTitleObj;
        }
        //第10道题
        $this->getNoteByIndex($note,10);
        //第18道题
        $this->getNoteByIndex($note,14);
        $this->getNutriContact($note);
        $obj = $this->dwResistAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note);
        return $obj;
    }*/


}